package ar.com.e2solver.solver.localsearch;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import ar.com.e2solver.exception.BusinessException;
import ar.com.e2solver.solver.Individual;
import ar.com.e2solver.solver.Population;
import ar.com.e2solver.solver.operator.impl.SwapAndRotateMutationOperator;

public final class SimpleHillClimbing implements HillClimbing {
	
	private static SimpleHillClimbing instance = new SimpleHillClimbing();

	private SimpleHillClimbing(){}
	
	public static SimpleHillClimbing getInstance(){
		return instance;
	}
	
	public List<Individual> climb(List<Individual> selectedIndividuals) throws BusinessException {
		List<Individual> result = new ArrayList<Individual>();
		
		for (Iterator<Individual> iterator = selectedIndividuals.iterator(); iterator.hasNext();) {
			Individual individual = iterator.next();
			result.add(climb(individual));
		}
		
		return result;
	}

	private Individual climb(Individual individual) throws BusinessException {
		Individual result = individual;
		int cant = individual.getPuzzle().getRowsNumber() * individual.getPuzzle().getColumnNumbers();
		int cantDeep = individual.getPuzzle().getRowsNumber() * individual.getPuzzle().getColumnNumbers() * 10;
		
		for (int i = 0; i < cantDeep; i++) {	
			Population population = new Population();
			
			for (int j = 0; j < cant; j++) {
				population.add(getNeighbor(result));
			}
			result = population.getBestIndividual();
		}
		
		return result;
	}

	protected Individual getNeighbor(Individual individual) throws BusinessException {
		Individual result;
		
		result = SwapAndRotateMutationOperator.getInstance().operate(individual);
		return result;
	}
}
